/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.persistence.hibernate.core;

import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.model.core.Sequence;
import com.blandware.atleap.persistence.core.SequenceDAO;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Hibernate implementation of SequenceDAO</p>
 * <p><a href="SequenceDAOHibernate.java.html"><i>View Source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version : $Revision: 1.3 $ : 2007/12/17 13:38:25 $
 */
public class SequenceDAOHibernate extends BaseDAOHibernate implements SequenceDAO {

	// ~ CRUD Methods ================================================================

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceDAO#createSequence(com.blandware.atleap.model.core.Sequence, com.blandware.atleap.model.core.Localizable) 
	 */
	public Long createSequence(Sequence sequence, Localizable localizable) {
		localizable.addSequence(sequence);
		return (Long) getHibernateTemplate().save(sequence);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceDAO#retrieveSequence(Long)
	 */
	public Sequence retrieveSequence(Long sequenceId) {
		return (Sequence) getHibernateTemplate().get(Sequence.class, sequenceId);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceDAO#updateSequence(com.blandware.atleap.model.core.Sequence, com.blandware.atleap.model.core.Localizable) 
	 */
	public void updateSequence(Sequence sequence, Localizable localizable) {
		Sequence oldSequence = localizable.updateSequence(sequence);
        removeFromCache(oldSequence);
		getHibernateTemplate().update(sequence);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceDAO#deleteSequence(com.blandware.atleap.model.core.Sequence) 
	 */
	public void deleteSequence(Sequence sequence) {
		getHibernateTemplate().delete(sequence);
		sequence.getOwner().removeSequence(sequence);
	}

	// ~ Additional methods ================================================================


	/**
	 * @see com.blandware.atleap.persistence.core.SequenceDAO#listSequences(com.blandware.atleap.common.util.QueryInfo) 
	 */
	public PartialCollection listSequences(QueryInfo queryInfo) {
		String whereClause = "";
		String orderByClause = "";
		if ( queryInfo != null ) {
			whereClause = queryInfo.getWhereClause();
			orderByClause = queryInfo.getOrderByClause();
			if ( whereClause != null && whereClause.length() != 0 ) {
				whereClause = " and " + whereClause;
			} else {
				whereClause = "";
			}
			if ( orderByClause != null && orderByClause.length() != 0 ) {
				orderByClause = " order by " + orderByClause;
			} else {
				orderByClause = "";
			}
		}

		Long ownerId = null;
		if ( queryInfo != null ) {
			if ( queryInfo.getQueryParameters() != null ) {
				ownerId = (Long) queryInfo.getQueryParameters().get("ownerId");
			}
		}
		List list;
		Integer total = null;
		ArrayList args = new ArrayList();
		String hqlPart;
		if ( ownerId != null ) {
			hqlPart = "from Sequence s where (s.owner.id = ?)" + whereClause;
			args.add(ownerId);
		} else {
            if (whereClause.length() > 0) {
                hqlPart = "from Sequence s where " + whereClause;
            } else {
                hqlPart = "from Sequence s ";
            }
        }
		if ( queryInfo != null && (queryInfo.getLimit() != null || queryInfo.getOffset() != null) ) {
			String hqlForTotal = "select count(s.id) " + hqlPart;
			total = findUniqueIntegerResult(hqlForTotal, args.toArray());
			if ( total == null ) {
				total = new Integer(0);
			}
		}
        // If we don't have any info about the total number of results yet or
        // we know that there's something that will be found, then fetch data
		if ( total == null || total.intValue() > 0 ) {
			String hql = "select s " + hqlPart + orderByClause;
			list = executeFind(hql, queryInfo, args.toArray());
			if ( total == null ) {
				total = new Integer(list.size());
			}
		} else {
			list = new ArrayList();
		}
		return new PartialCollection(list, total);

	}

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceDAO#hasDuplicates(com.blandware.atleap.model.core.Sequence, Long) 
	 */
	public boolean hasDuplicates(Sequence sequence, Long ownerId) {

		ArrayList args = new ArrayList();
		args.add(sequence.getIdentifier());
		args.add(ownerId);

		String hql = "select count(s.id) from Sequence s where s.identifier = ? and s.owner.id = ?";
		if ( sequence.getId() != null ) {
			hql += " and s.id != ?";
			args.add(sequence.getId());
		}

		int count = (findUniqueIntegerResult(hql, args.toArray())).intValue();

		return count > 0;
	}

	// ~ Finders ================================================================

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceDAO#findSequenceByLayoutDefinition(String, String) 
	 */
	public Sequence findSequenceByLayoutDefinition(String identifier, String definition) {
		return (Sequence) findUniqueResult("select sequence from Layout layout inner join layout.sequences sequence where layout.definition = ? and sequence.identifier = ?", new Object[]{definition, identifier});
	}

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceDAO#findSequenceByPageUri(String, String)
	 */
	public Sequence findSequenceByPageUri(String identifier, String uri) {
        return (Sequence) findUniqueResult("select sequence from Page page inner join page.sequences sequence where page.uri = ? and sequence.identifier = ?", new Object[]{uri, identifier});
	}

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceDAO#findSequenceByLocalizable(String, com.blandware.atleap.model.core.Localizable)
	 */
	public Sequence findSequenceByLocalizable(String identifier, Localizable localizable) {
		return (Sequence) findUniqueResult("from Sequence s where s.identifier = ? and s.owner = ?", new Object[]{identifier, localizable});
	}
}